
import matplotlib.pyplot as plt
import re



def parse_result(path):
	f=open(path)
	lines = f.readlines()
	f.close()
	for i in range(1,len(lines)+1):
		line = lines[-i]
		mat = re.match("\('exec_count', (\d+)?\)",line)
		if mat:
			exec_count = int(mat.groups()[0])
			break
	for i in range(1,len(lines)+1):
		line = lines[-i]
		mat = re.match("\('time_count', (.+)?\)",line)
		if mat:
			time_count = float(mat.groups()[0])
			break
	ts = []
	for i in range(0,len(lines)):
		line = lines[i]
		mat = re.match("\('graph exec time', (.+)?\)",line)
		if mat:
			graph_exec_time = float(mat.groups()[0])
			ts.append(graph_exec_time)
	graph_exec_time_sum = sum(ts)
	graph_exec_count = len(ts)
	ret = exec_count,time_count,graph_exec_count,graph_exec_time_sum
	print(ret)
	return ret


def parse_data(lambda_list,dirname,testcount = 4):
	# exec_count_list
	# time_count_list
	# graph_exec_count_list
	# graph_exec_time_sum_list
	# time_count_list / exec_count_list
	# graph_exec_time_sum_list / graph_exec_count_list

	data = [[] for i in range(6)]
	for parm in lambda_list:
		a = [0.0 for i in range(6)]
		for testnum in range(1,testcount+1):
			path = 'result/%s/Geant-2012-hn9-hn23-lambda-%d-%d.txt'%(dirname,parm,testnum)
			r = parse_result(path)
			for i in range(4):
				a[i]+=r[i]
			a[4]+= r[1]/r[0]
			a[5]+= r[3]/r[2]
		for i in range(6):
			data[i].append(a[i]/testcount)
	return data


title = ["operation_exec_number",
	"time_count",
	"graph_exec_number",
	"graph_exec_time_sum",
	"time_count / operation_exec_number",
	"graph_exec_time_sum / graph_exec_number"]

filename = ["operation_exec_number",
	"time_count",
	"graph_exec_number",
	"graph_exec_time_sum",
	"time_count#operation_exec_number",
	"graph_exec_time_sum#graph_exec_number"]

ylabels = [None,
	"time (s)",
	None,
	"time (s)",
	"average time (s)",
	"average time (s)"
]

lambda_list = range(10,110,10)

data1 = parse_data(lambda_list,'serialresult')
data2 = parse_data(lambda_list,'mergeresult')

plt.clf()
d1 = [1000/t for t in data1[1]]
d2 = [1000/t for t in data2[1]]
plt.plot(lambda_list,d1,'r*-',label='series')
plt.plot(lambda_list,d2,'b.-',label='simple merge')
plt.title("execution rate")
plt.xlabel("$\lambda$ ($s^{-1}$)")
plt.ylabel("execution rate($s^{-1}$)")
plt.savefig('figs/execution_rate.png')
plt.show()

exit(0)



for i in range(6):
	plt.clf()
	plt.plot(lambda_list,data1[i],'r*-',label='series')
	plt.plot(lambda_list,data2[i],'b.-',label='simple merge')
	plt.title(title[i])
# 	plt.xticks(lambda_list)
	plt.xlabel("$\lambda$ ($s^{-1}$)")
	if ylabels[i]:
		plt.ylabel(ylabels[i])
	plt.legend()
	# plt.savefig('figs/%s.png'%filename[i])
	plt.show()


plt.clf()
plt.plot(lambda_list,data1[1],'r*-')
plt.plot(lambda_list,data2[1],'b.-')
plt.plot(lambda_list,data1[3],'r*--')
plt.plot(lambda_list,data2[3],'b.--')
plt.title("time_count (solid) graph_exec_time_sum (dashed)")
plt.xlabel("$\lambda$ ($s^{-1}$)")
plt.ylabel("time (s)")
# plt.savefig('figs/13.png')
plt.show()